package com.study.entity;

import com.study.frame.TankWarFrame;
import com.study.manager.ResourceManager;
import com.study.utils.ApplicationComponent;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * 子弹
 * @Author ZhuHJay
 * @Date 2021/9/14 16:25
 */
public class Bullet {

    /** 子弹的坐标 **/
    private int x, y;

    /** 子弹的大小 **/
    public static int BULLET_WIDTH;
    public static int BULLET_HEIGHT;

    /** 子弹的资源图片 **/
    private BufferedImage image;

    /** 移动速度 **/
    private static final int SPEED = 20;

    /** 运动方向 **/
    private Direction direction;

    /** 该子弹属于哪个坦克 **/
    private Tank tank;

    /** 该子弹是否存活 **/
    private boolean living = true;

    /** 坦克的矩形 **/
    private Rectangle rectangle;

    public Bullet(int x, int y, Direction direction, BufferedImage image, Tank tank){
        this.x = x;
        this.y = y;
        this.direction = direction;
        this.image = image;
        this.tank = tank;
        BULLET_WIDTH = image.getWidth();
        BULLET_HEIGHT = image.getHeight();
        rectangle = new Rectangle(x, y, BULLET_WIDTH, BULLET_HEIGHT);
    }

    /** 子弹绘画 **/
    public void paint(Graphics graphics){
        // 判断是否需要进行绘画
        if( !isLiving() ){
            ApplicationComponent.getBean(TankWarFrame.class)
                    .removeBullet(this);
            return;
        }
        Color color = graphics.getColor();
        graphics.drawImage(image, x, y, null);
        move();
        graphics.setColor(color);
    }

    /** 子弹移动 **/
    private void move(){
        // 判断当前的方向, 然后进行坐标的移动, 如果超出了界面就让他消失
        switch ( direction ){
            case DOWN:
                y += SPEED;
                if( y > TankWarFrame.FRAME_HEIGHT){
                    living = false;
                }
                break;
            case UP:
                y -= SPEED;
                if( y < 0 ){
                    living = false;
                }
                break;
            case LEFT:
                x -= SPEED;
                if( x < 0 ){
                    living = false;
                }
                break;
            case RIGHT:
                x += SPEED;
                if( x > TankWarFrame.FRAME_WIDTH ){
                    living = false;
                }
                break;
            default:
                break;
        }
        rectangle.setBounds(x, y, BULLET_WIDTH, BULLET_HEIGHT);
    }

    /** 碰撞检测, 碰撞坦克 **/
    public void bumpWith(Tank tank) {
        if( rectangle.intersects(tank.getRectangle()) ){
            Tank myTank = ApplicationComponent.getBean("myTank");
            // 爆炸逻辑如下
            // 如果子弹是被控制坦克的, 坦克是敌机
            if( this.tank == myTank && !tank.isControl() ){
                tank.setLiving(false);
                living = false;
            }
        }
    }

    public boolean isLiving() {
        return living;
    }
}
